package com.wangsd.web.face.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.wangsd.common.basicbean.Result;
import com.wangsd.web.common.service.UploadFileService;
import com.wangsd.web.face.entity.AppVersion;
import com.wangsd.web.face.entity.Device;
import com.wangsd.web.face.service.AppVersionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author generator
 * @since 2019-10-28
 */
@RestController
@RequestMapping("/face/appVersion")
public class AppVersionController {

    @Autowired
    AppVersionService appVersionService;

    @Autowired
    UploadFileService uploadFileService;

    @GetMapping("/select/{id}")
    public Result select(@PathVariable Long id) {
        AppVersion appVersion = appVersionService.getById(id);
        return Result.success(appVersion);
    }

    @PostMapping("/selectPage/{pageNum}/{pageSize}")
    public Result selectPage(@PathVariable Integer pageNum,
                             @PathVariable Integer pageSize,
                             @RequestBody AppVersion entity) {
        IPage<AppVersion> appVersionIPage = appVersionService.selectList(pageNum, pageSize, entity);
        return Result.success(appVersionIPage);
    }
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable Long id) {
        appVersionService.removeById(id);

        /*删除阿里云上文件*/
        AppVersion byId = appVersionService.getById(id);
        if(byId!=null){
            uploadFileService.deleteFile(byId.getFileName());
        }
        return Result.success();
    }

    @PostMapping("/save")
    public Result save(@RequestBody AppVersion entity) {
        if(StringUtils.isBlank(entity.getVersionNo())){
            return Result.fail("版本号不能为空");
        }
        if(entity.getId() == null ){
            AppVersion appVersion = appVersionService.selectByVersionNo(entity.getVersionNo());
            if(appVersion != null){
                return Result.fail("版本已存在");
            }
        }
        appVersionService.addOrUpdate(entity);
        return Result.success();
    }

    @GetMapping("/push/{id}")
    public Result push(@PathVariable Long id) {
        if(id == null ){
            return Result.fail("参数错误");
        }
        AppVersion appVersion = appVersionService.getById(id);

        if(appVersion == null ){
            return Result.fail("数据错误");
        }
        //组装修改参数
        AppVersion upVersion = new AppVersion();
        upVersion.setId(appVersion.getId());
        upVersion.setIsPush(appVersion.getIsPush() == 0 ? 1 : 0);
        upVersion.setPushTime(new Date());

        appVersionService.addOrUpdate(upVersion);
        return Result.success();
    }
}

